package com.sanhe.rfmuscle.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.plata.base.aclr.utils.NetworkUtils;
import com.plata.base.utils.WeakHandler;
import com.sanhe.rfmuscle.R;


import java.lang.ref.WeakReference;

public class WifiStateView extends AppCompatImageView {

    private WifiManager wifiManager;

    private WifiHandler wifiHandler;

    //没有开启Wifi或开启了Wifi但没有连接
    private static final int LEVEL_NONE = 0;

    //Wifi信号等级（最弱）
    private static final int LEVEL_1 = 1;

    //Wifi信号等级
    private static final int LEVEL_2 = 2;

    //Wifi信号等级
    private static final int LEVEL_3 = 3;

    //Wifi信号等级（最强）
    private static final int LEVEL_4 = 4;

    private final String TAG = "WifiStateView";

    private static class WifiHandler extends WeakHandler {

        //虚引用
        private WeakReference<WifiStateView> stateViewWeakReference;

        WifiHandler(WifiStateView wifiStateView) {
            stateViewWeakReference = new WeakReference<>(wifiStateView);
        }

        @Override
        public void handleMessage(Message msg) {
            WifiStateView wifiStateView = stateViewWeakReference.get();
            if (wifiStateView == null) {
                return;
            }
            switch (msg.what) {
                case LEVEL_1:
                case LEVEL_2:
                case LEVEL_3:
                    wifiStateView.setImageResource(R.mipmap.muscle_wifi1);
                    break;
                case LEVEL_NONE:
                default:
                    wifiStateView.setImageResource(R.mipmap.muscle_wifi2);
                    break;
            }
        }
    }

    private boolean isConnect() {
        try {
            return wifiManager.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    private BroadcastReceiver wifiStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "action " + intent.getAction());
            switch (intent.getAction()) {
                case WifiManager.WIFI_STATE_CHANGED_ACTION:
                    if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING
                            || wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED
                            || !isConnect()) {
                        wifiHandler.sendEmptyMessage(LEVEL_NONE);
                    }
                    break;
                case WifiManager.RSSI_CHANGED_ACTION:
                    if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED
                            || wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING) {
                        wifiHandler.sendEmptyMessage(LEVEL_NONE);
                        return;
                    }
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 4);
                    Log.e(TAG, "level:" + level);
                    wifiHandler.sendEmptyMessage(level);
                    break;
            }
        }
    };

    public WifiStateView(Context context) {
        this(context, null);
    }

    public WifiStateView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WifiStateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiHandler = new WifiHandler(this);
        refresh();
    }

    public void refresh() {
        if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING
                || wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED
                || !isConnect()
                || !NetworkUtils.hasConnect(getContext())) {
            setImageResource(R.mipmap.muscle_wifi2);
        } else {
            setImageResource(R.mipmap.muscle_wifi1);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        IntentFilter intentFilter = new IntentFilter();
        //Wifi连接状态变化
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        //Wifi信号强度变化
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        getContext().registerReceiver(wifiStateReceiver, intentFilter);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        wifiHandler.removeCallbacksAndMessages(null);
        getContext().unregisterReceiver(wifiStateReceiver);
    }
}